package routers

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"web-collect-server/router/api"
)

// InitRouter 初始化路由
func InitRouter() *gin.Engine {
	r := gin.New()
	r.Use(Cors())         // 开启跨域中间件
	r.Use(gin.Logger())   // 写日志
	r.Use(gin.Recovery()) // 全局异常处理
	api.InitApi(r)        // 初始化 api
	api.InitHeart(r)      // 初始化 心跳 api

	return r
}

func Cors() gin.HandlerFunc {
	// 允许跨域
	return func(c *gin.Context) {
		method := c.Request.Method
		origin := c.Request.Header.Get("Origin") //请求头部
		if origin != "" {
			// 可将将* 替换为指定的域名
			c.Header("Access-Control-Allow-Origin", "*")
			c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE")
			c.Header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization")
			c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Cache-Control, Content-Language, Content-Type")
			c.Header("Access-Control-Allow-Credentials", "true")
		}

		if method == "OPTIONS" {
			c.AbortWithStatus(http.StatusNoContent)
		}

		c.Next()
	}
}
